class MediaFormatException < StandardError
end

class VideoConversionWorker < BackgrounDRb::MetaWorker
  set_worker_name :video_conversion_worker

  def create(args = nil)
    #called when the worker is loaded
  end

  def do_work args
    # This method is called in it's own new thread when you
    # call new worker. args is set to :args
    logger.info("Entered VideoConversionWorker.")
    video_file = args[:absolute_path]
    logger.info(video_file)
    logger.info("File: " + video_file)
    id = args[:video_id]
    logger.info("Video id: " + id)
    the_video = VideoFile.find(id.to_i)
    the_video.save
    begin
      `nice -n +19 ffmpeg -i #{video_file} -ss 00:00:03 -t 00:00:01 -vcodec mjpeg -vframes 1 -an -f rawvideo -s 480x360 #{video_file}.jpg`
      `nice -n +19 ffmpeg -i #{video_file} -ss 00:00:03 -t 00:00:01 -vcodec mjpeg -vframes 1 -an -f rawvideo -s 200x150 #{video_file}.small.jpg`
      if args[:highdef]
#        execute_ffmpeg("nice -n +19 ffmpeg -i #{video_file} -y -s 640x480 -an -pass 1 -vcodec libx264 -threads 4 -b 1024kbps -flags +loop -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -me epzs -subq 1 -trellis 0 -refs 1 -bf 3 -b_strategy 1 -coder 1 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 #{video_file}.mp4 2>&1", the_video, 3, 0)
#        execute_ffmpeg("nice -n +19 ffmpeg -i #{video_file} -y -s 640x480 -acodec libfaac -ab 128k -pass 2 -vcodec libx264 -threads 4 -b 1024kbps -flags +loop -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -flags2 +mixed_refs -me umh -subq 5 -trellis 1 -refs 5 -bf 3 -b_strategy 1 -coder 1 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 #{video_file}.mp4 2>&1", the_video, 3, 1)
#        execute_ffmpeg("nice -n +19 ffmpeg -i #{video_file} -ab 48 -ar 22050 -s 480x360 -y #{video_file}.flv 2>&1", the_video, 3, 2)
        execute_ffmpeg("nice -n +19 ffmpeg -i #{video_file} -s 640x480 -vcodec libx264 -r 25 -g 25 -keyint_min 25 -coder ac -me full -me_range 16 -subq 5 -sc_threshold 40 -acodec libfaac -ab 96000 -ar 22500 -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -i_qfactor 0.71 -b_strategy 1 -crf 30 -y #{video_file}.mp4 2>&1", the_video, 2, 0)
        execute_ffmpeg("nice -n +19 ffmpeg -i #{video_file} -ab 48 -ar 22050 -s 480x360 -y #{video_file}.flv 2>&1", the_video, 2, 1)
        `mv #{video_file}.mp4 #{video_file}.mp4.flv`
      else
        execute_ffmpeg("nice -n +19 ffmpeg -i #{video_file} -ab 48 -ar 22050 -s 480x360 -y #{video_file}.flv 2>&1", the_video, 1, 0)
      end
    rescue
      logger.info("could not convert video, deleted sources")
      the_video.processing_status = 500
      the_video.save
      `rm -rf #{video_file}*`
      exit 1
    end
    the_video.save
    logger.info("done worker code")
    exit 1
  end

def execute_ffmpeg(command, video, times=1, completepass=0)
  progress = nil
  IO.popen(command) do |pipe|
    pipe.each("\r") do |line|
      puts line
      $defout.flush
      logger.info(line)
      if line =~ /Duration: (\d{2}):(\d{2}):(\d{2}).(\d{1})/
        @duration = (($1.to_i * 60 + $2.to_i) * 60 + $3.to_i) * 10 + $4.to_i
        print "DURATION: #{@duration}\n"
      end
      if line =~ /time=(\d+).(\d+)/
        $defout.flush
        if !@duration.nil? and @duration != 0
          c = ($1.to_i * 10 + $2.to_i)
          c = c + (completepass * @duration)
          p = ( c * 100 / ( @duration * times ) )
          $defout.flush
        else
          p = 0
        end
        p = 100 if p > 100
        if progress != p
          progress = p
          video.processing_status = progress
          video.save
          print "PROGRESS: #{progress}\n"
          $defout.flush
        end
      end
    end
  end
  raise MediaFormatException if $?.exitstatus != 0
  unless times == (completepass - 1)
    video.processing_status = 200
    video.media.upload_complete = 1
    video.media.save
    video.save
  end
end

end
